package com.wobito.controller.admin;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wobito.common.constants.*;
import com.wobito.common.utils.DateUtils;
import com.wobito.common.utils.ResultUtils;
import com.wobito.pojo.bean.Cabinet;
import com.wobito.pojo.bean.CabinetLat;
import com.wobito.pojo.dto.cabinet.CabinetDTO;
import com.wobito.pojo.enums.IsDeletedEnum;
import com.wobito.pojo.vo.cabinet.AddCabinetVO;
import com.wobito.pojo.vo.cabinet.CabinetVO;
import com.wobito.pojo.vo.cabinet.UpdateCabinetVO;
import com.wobito.pojo.vo.cabinetLat.AddCabinetLatVO;
import com.wobito.pojo.vo.cabinetLat.UpdateCabinetLatVO;
import com.wobito.service.CabinetLatService;
import com.wobito.service.ICabinetService;
import com.wobito.system.aspect.OperLog;
import com.wobito.system.socket.WebSocketServer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * <p>
 * 柜子表 前端控制器
 * </p>
 *
 * @author lambyang
 * @since 2024-07-23
 */
@RestController
@RequestMapping("/manage/cabinetManage")
@Api(tags = "柜子管理")
public class CabinetManageController {

    @Autowired
    private ICabinetService cabinetService;
    @Autowired
    private CabinetLatService cabinetLatService;
    @Autowired
    private WebSocketServer webSocketServer;

    @GetMapping()
    @ApiOperation(value = "根据条件查询柜子")
    @OperLog(thing = "根据条件查询柜子")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN','NOMAL_ADMIN')")
    public BaseResponse getCabinetList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                       @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                       @RequestParam(value = "areaId", required = false) Long areaId,
                                       @RequestParam(value = "queryName", required = false) String queryName,
                                       @RequestParam(value = "isDeleted", required = false) Integer isDeleted) {
        TableDataInfo dataInfo = new TableDataInfo();
        PageHelper.startPage(pageNum, pageSize);
        List<CabinetDTO> cabinetDTOS = cabinetService.selectCabinetList(new CabinetVO(areaId, queryName, isDeleted));
        dataInfo.setRows(cabinetDTOS);
        dataInfo.setTotal(new PageInfo(cabinetDTOS).getTotal());
        return ResultUtils.success(dataInfo);
    }

    @GetMapping("/getCabinetList")
    @OperLog(thing = "获取柜子下拉框")
    @ApiOperation(value = "获取柜子(ID-NAME)", notes = "下拉框选择等用，只会返回正常状态的")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN','NOMAL_ADMIN')")
    public BaseResponse getCabinetBriefList(@RequestParam(value = "areaId") Long areaId) {
        return ResultUtils.success(cabinetService.selectBrief(areaId));
    }

    @GetMapping("/getLatByCabinet/{id}")
    @ApiOperation(value = "根据柜子ID获取柜格")
    @OperLog(thing = "根据柜子ID获取柜格")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN','NOMAL_ADMIN')")
    public BaseResponse getLatByCabinet(@PathVariable("id") Long id) {
        return ResultUtils.success(cabinetLatService.selectCabinetLatList(id));
    }

    @GetMapping("/getCabinetOnline/{cabinetId}")
    @ApiOperation(value = "实时检测柜子是否在线")
    @OperLog(thing = "获取柜子是否在线")
    public BaseResponse getCabinetOnline(@PathVariable("cabinetId") Long cabinetId) {
        String isOnline = cabinetService.selectCabinetIsOnlineByCode(cabinetId);
        return ResultUtils.success(isOnline);
    }

    @GetMapping("/getLatList")
    @ApiOperation(value = "根据柜子ID获取柜格(ID-NAME)", notes = "下拉框选择等用，只会返回正常状态的")
    @OperLog(thing = "根据柜子ID获取柜格下拉框")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN','NOMAL_ADMIN')")
    public BaseResponse getLatList(@RequestParam(value = "cabinetId") Long cabinetId) {
        return ResultUtils.success(cabinetLatService.selectBrief(cabinetId));
    }

    @PutMapping()
    @ApiOperation(value = "添加柜子")
    @OperLog(thing = "添加柜子")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN','NOMAL_ADMIN')")
    public BaseResponse addCabinet(@Valid @RequestBody AddCabinetVO addCabinetVO) {
        Cabinet cabinet = cabinetService.getOne(new LambdaQueryWrapper<Cabinet>().eq(Cabinet::getName, addCabinetVO.getName()));
        if (ObjectUtil.isNotEmpty(cabinet)) {
            throw new BusinessException(ErrorCode.REPEATPARAMS_ERROR, "柜子名称已存在");
        }
        return ResultUtils.success(cabinetService.insertCabinet(addCabinetVO));
    }

    @PutMapping("/addCabinetLat")
    @ApiOperation(value = "添加柜格")
    @OperLog(thing = "添加柜格")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN','NOMAL_ADMIN')")
    public BaseResponse addCabinetLat(@Valid @RequestBody AddCabinetLatVO addCabinetVO) {
        CabinetLat cabinetLat = cabinetLatService.getOne(new LambdaQueryWrapper<CabinetLat>().or(w -> {
                    w.eq(CabinetLat::getCode, addCabinetVO.getCode());
                    w.or().eq(CabinetLat::getName, addCabinetVO.getName());
                })
                .eq(CabinetLat::getCabinetId, addCabinetVO.getCabinetId()));
        if (ObjectUtil.isNotEmpty(cabinetLat)) {
            throw new BusinessException(ErrorCode.REPEATPARAMS_ERROR, "该柜下已有存在此编号或名称的柜格");
        }
        return ResultUtils.success(cabinetLatService.insertCabinetLat(addCabinetVO));
    }

    @PutMapping("/startCabinet/{id}")
    @ApiOperation(value = "启用柜子")
    @OperLog(thing = "启用柜子")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN','NOMAL_ADMIN')")
    public BaseResponse startCabinet(@PathVariable("id") Long id) {
        Cabinet cabinet = cabinetService.getById(id);
        webSocketServer.sendMessage(cabinet.getSequenceCode(), SysConstants.ENABLE_CABINET_STATE);
        return ResultUtils.success(cabinetService.updateById(new Cabinet(id, IsDeletedEnum.NORMAL.getCode())));
    }

    @PutMapping("/startLat/{id}")
    @ApiOperation(value = "启用柜格")
    @OperLog(thing = "启用柜格")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN','NOMAL_ADMIN')")
    public BaseResponse startLat(@PathVariable("id") Long id) {
        return ResultUtils.success(cabinetLatService.updateById(new CabinetLat(id, IsDeletedEnum.NORMAL.getCode())));
    }

    @PostMapping()
    @ApiOperation(value = "修改柜子")
    @OperLog(thing = "修改柜子")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN','NOMAL_ADMIN')")
    public BaseResponse updateCabinet(@Valid @RequestBody UpdateCabinetVO updateCabinetVO) {
        Cabinet cabinet = cabinetService.getOne(new LambdaQueryWrapper<Cabinet>().eq(Cabinet::getName, updateCabinetVO.getName()));
        if (ObjectUtil.isNotEmpty(cabinet) && !cabinet.getId().equals(updateCabinetVO.getId())) {
            throw new BusinessException(ErrorCode.REPEATPARAMS_ERROR, "柜子名称已存在");
        }
        return ResultUtils.success(cabinetService.updateCabinet(updateCabinetVO));
    }

    @PostMapping("/updateCabinetLat")
    @ApiOperation(value = "修改柜格")
    @OperLog(thing = "修改柜格")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN','NOMAL_ADMIN')")
    public BaseResponse updateCabinetLat(@Valid @RequestBody UpdateCabinetLatVO updateCabinetLatVO) {
        CabinetLat cabinetLat = cabinetLatService.getOne(new LambdaQueryWrapper<CabinetLat>().or(w -> {
                    w.eq(CabinetLat::getCode, updateCabinetLatVO.getCode());
                    w.or().eq(CabinetLat::getName, updateCabinetLatVO.getName());
                })
                .eq(CabinetLat::getCabinetId, updateCabinetLatVO.getCabinetId()));
        if (ObjectUtil.isNotEmpty(cabinetLat) && !cabinetLat.getId().equals(updateCabinetLatVO.getId())) {
            throw new BusinessException(ErrorCode.REPEATPARAMS_ERROR, "柜格名称已存在");
        }
        return ResultUtils.success(cabinetLatService.updateLat(updateCabinetLatVO));
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "停用柜子")
    @OperLog(thing = "停用柜子")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN','NOMAL_ADMIN')")
    public BaseResponse delCabinet(@PathVariable("id") Long id) {
        Cabinet cabinet = cabinetService.getById(id);
        webSocketServer.sendMessage(cabinet.getSequenceCode(), SysConstants.STOP_CABINET_STATE);
        return ResultUtils.success(cabinetService.updateById(new Cabinet(id, IsDeletedEnum.DELETED.getCode(), DateUtils.getNowDate())));
    }

    @DeleteMapping("/delLat/{id}")
    @ApiOperation(value = "停用柜格")
    @OperLog(thing = "停用柜格")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN','NOMAL_ADMIN')")
    public BaseResponse delLat(@PathVariable("id") Long id) {
        return ResultUtils.success(cabinetLatService.updateById(new CabinetLat(id, IsDeletedEnum.DELETED.getCode(), DateUtils.getNowDate())));
    }
}
